package servlet;

import dao.CommentDao;
import dao.CommentDaoImpl;
import org.json.JSONObject;
import pojo.Comment;
import redis.RedisDao;
import redis.RedisDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;

import static util.JwtUtil.validateJWT;

public class CmtServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String token=req.getParameter("token");
        int result=0;
        JSONObject object=new JSONObject();
        if(validateJWT(token)){
            JSONObject cmt=new JSONObject(req.getParameter("comment"));
            System.out.println(cmt);
            int postId=cmt.getInt("postId");
            int account=cmt.getInt("account");
            String content=cmt.getString("content");
            Comment comment=new Comment();
            comment.setPostId(postId);
            comment.setCommentAccount(account);
            comment.setCommentContent(content);
            comment.setCommentTime(new Timestamp(System.currentTimeMillis()));
            CommentDao dao=new CommentDaoImpl();
            int commentId=dao.insertComment(comment);
            comment.setCommentId(commentId);
            RedisDao dao1=new RedisDaoImpl();

            if(dao1.addCom(comment)){
                JSONObject cmtObj=new JSONObject();
                cmtObj.put("postId",comment.getPostId());
                cmtObj.put("commentAccount",comment.getCommentAccount());
                cmtObj.put("commentContent",comment.getCommentContent());
                cmtObj.put("commentTime",comment.getCommentTime());
                object.put("comment",cmtObj);
                result=1;
            }
        }else{
            System.out.println("令牌有误，告你非法入侵");
        }
        resp.setContentType("text/json; charset=utf-8");
//        输出数据
        object.put("result",result);
        PrintWriter out = resp.getWriter();
        out.print(object);
    }
}
